package api

import (
	"smoot-code/service/data"
	"smoot-code/service/types"
	"sync"
)

type TemplateApi struct {
	data data.Data
}

var template *TemplateApi
var onceTemplate sync.Once

func (s *TemplateApi) GetTemplates() types.Resp {
	templates, err := template.data.GetTemplates()
	msg := "Success"
	success := true
	if err != nil {
		success = false
		msg = err.Error()
	}
	return types.Resp{
		Success: success,
		Data:    templates,
		Msg:     msg,
	}
}

func (s *TemplateApi) AddTemplate(templates types.Template) types.Resp {
	key, err := s.data.AddTemplate(templates)
	msg := "Success"
	success := true
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Data:    key,
		Msg:     msg,
	}
}

func (s *TemplateApi) EditTemplate(templates types.Template) types.Resp {
	key, err := s.data.EditTemplate(templates)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Data:    key,
		Msg:     msg,
	}
}

func (s *TemplateApi) DeleteTemplate(templates types.Template) types.Resp {
	key, err := s.data.DeleteTemplate(templates)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Data:    key,
		Msg:     msg,
	}
}

func (s *TemplateApi) CopyTemplate(templates types.Template) types.Resp {
	key, err := s.data.CopyTemplate(templates)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Data:    key,
		Msg:     msg,
	}
}

func NewTemplateApi(datas data.Data) *TemplateApi {
	if template == nil {
		onceTemplate.Do(func() {
			template = &TemplateApi{datas}
		})
	}
	return template
}
